import { useState, useCallback, useEffect } from 'react';
import { GameState, Player, Position, GameMode } from '../types/game';
import {
  initializeGame,
  placePiece,
  checkGameEnd,
  switchPlayer,
  isEmpty,
} from '../utils/gameLogic';
import { getSmartAIMove } from '../utils/smartAI';

export const useGame = () => {
  const [gameState, setGameState] = useState<GameState>(() => initializeGame('pvp'));
  const [isAIThinking, setIsAIThinking] = useState(false);

  // 开始新游戏
  const startNewGame = useCallback((mode: GameMode) => {
    setGameState(initializeGame(mode));
    setIsAIThinking(false);
  }, []);

  // 玩家移动
  const makeMove = useCallback(async (row: number, col: number): Promise<boolean> => {
    // 获取当前状态快照
    setGameState(currentState => {
      if (currentState.gameStatus !== 'playing' || !isEmpty(currentState.board, row, col)) {
        return currentState;
      }

      try {
        // 放置玩家棋子
        const newBoard = placePiece(currentState.board, row, col, currentState.currentPlayer);
        const lastMove = { row, col };
        
        // 检查游戏是否结束
        const { winner, winningLine } = checkGameEnd(newBoard, lastMove);
        
        return {
          ...currentState,
          board: newBoard,
          currentPlayer: switchPlayer(currentState.currentPlayer),
          winner,
          winningLine,
          moveCount: currentState.moveCount + 1,
          lastMove,
          gameStatus: winner ? 'finished' : 'playing',
        };
      } catch (error) {
        console.error('Invalid move:', error);
        return currentState;
      }
    });

    return true;
  }, []);

  // AI移动
  const makeAIMove = useCallback(async () => {
    // 获取当前状态快照
    setGameState(currentState => {
      if (currentState.gameMode !== 'ai' || currentState.currentPlayer !== 'white' || currentState.gameStatus !== 'playing') {
        return currentState;
      }

      setIsAIThinking(true);
      return currentState;
    });

    // 模拟AI思考时间
    await new Promise(resolve => setTimeout(resolve, 100));

    try {
      // 再次获取最新状态
      const currentState = gameState;
      const aiMove = getSmartAIMove(currentState.board, 'white');
      
      if (!aiMove) {
        setIsAIThinking(false);
        return;
      }

      const newBoard = placePiece(currentState.board, aiMove.row, aiMove.col, 'white');
      const { winner, winningLine } = checkGameEnd(newBoard, aiMove);
      
      setGameState(prev => ({
        ...prev,
        board: newBoard,
        currentPlayer: switchPlayer(prev.currentPlayer),
        winner,
        winningLine,
        moveCount: prev.moveCount + 1,
        lastMove: aiMove,
        gameStatus: winner ? 'finished' : 'playing',
      }));

      setIsAIThinking(false);
    } catch (error) {
      console.error('AI move error:', error);
      setIsAIThinking(false);
    }
  }, [gameState]);

  // 当轮到AI时自动移动
  useEffect(() => {
    if (gameState.gameMode === 'ai' && gameState.currentPlayer === 'white' && gameState.gameStatus === 'playing') {
      makeAIMove();
    }
  }, [gameState.currentPlayer, gameState.gameMode, gameState.gameStatus, makeAIMove]);

  // 重置游戏
  const resetGame = useCallback(() => {
    setGameState(initializeGame(gameState.gameMode));
    setIsAIThinking(false);
  }, [gameState.gameMode]);

  // 返回模式选择
  const backToModeSelection = useCallback(() => {
    setGameState(prev => ({
      ...prev,
      gameStatus: 'selecting',
      gameMode: null,
    }));
    setIsAIThinking(false);
  }, []);

  return {
    gameState,
    isAIThinking,
    startNewGame,
    makeMove,
    resetGame,
    backToModeSelection,
  };
};